package org.bizming.medicine.service;

import java.util.List;

import org.bizming.base.BaseErrCode;
import org.bizming.base.BaseException;
import org.bizming.medicine.dao.MedicineDao;
import org.bizming.medicine.dao.ShipmentDao;
import org.bizming.medicine.model.Medicine;
import org.bizming.medicine.model.ShipmentMedicine;
import org.bizming.medicine.model.ext.ShipmentExt;
import org.bizming.medicine.model.help.ActionType;
import org.bizming.web.util.Helper;

public class ShipmentServiceImpl implements ShipmentService {

	private ShipmentDao shipmentDao;
	private MedicineDao medicineDao;

	@Override
	public boolean add(ShipmentMedicine t) throws Exception {
		if (!Helper.validate(t, ActionType.ADD)) {
			throw new BaseException(BaseErrCode.INVALIDATE);
		}
		boolean flag = shipmentDao.add(t);
		if (flag) {
			flag = medicineDao.decreCount(t.getMedicineId(), t.getAmount());
			if (!flag) {
				throw new Exception();
			}
		}

		return false;
	}

	public ShipmentDao getShipmentDao() {
		return shipmentDao;
	}

	public void setShipmentDao(ShipmentDao shipmentDao) {
		this.shipmentDao = shipmentDao;
	}

	public MedicineDao getMedicineDao() {
		return medicineDao;
	}

	public void setMedicineDao(MedicineDao medicineDao) {
		this.medicineDao = medicineDao;
	}

	@Override
	public List<ShipmentExt> selectList() {
		List<ShipmentExt> list = shipmentDao.selectList();
		if (!Helper.isEmpty(list)) {
			Medicine medicine;
			for (ShipmentExt t : list) {
				medicine = medicineDao.get(t.getMedicineId());
				t.setMedicine(medicine);
			}
		}
		return list;
	}

	@Override
	public ShipmentExt get(int id) {
		ShipmentExt t = shipmentDao.get(id);
		if (t != null) {
			Medicine medicine = medicineDao.get(t.getMedicineId());
			t.setMedicine(medicine);
			return t;
		}

		return null;
	}

	@Override
	public int count() {
		return shipmentDao.count();
	}

	@Override
	public boolean remove(int id) throws Exception {

		ShipmentExt t = shipmentDao.get(id);
		if (t != null) {
			boolean flag = shipmentDao.remove(id);
			if (flag) {
				flag = medicineDao.increCount(t.getId(), t.getAmount());
				if (!flag) {
					throw new Exception();
				}
				return true;
			}
		}

		return false;
	}

	@Override
	public boolean update(ShipmentMedicine t) {
		// TODO Auto-generated method stub
		return false;
	}

}
